/*
 * @Author: your name
 * @Date: 2021-04-19 13:55:02
 * @LastEditTime: 2021-07-29 10:50:46
 * @LastEditors: Myruun
 * @Description: In User Settings Edit
 * @FilePath: \serve\unit\mysql.ts
 */
const mysql = require("mysql");

const { config } = require("../config/default.ts");

const POOL = mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  port: config.database.PORT,
  database: config.database.DATABASE,
  charset: "UTF8MB4_GENERAL_CI",
});
const querys = (sql, values = "") => {
  return new Promise((resolve, reject) => {
    POOL.getConnection((err, conn) => {
      let obj = {
        code: 400,
        data: {
          msg: "和mysql数据库建立连接失败",
        },
      };
      if (err) {
        resolve(obj);
      } else {
        conn.query(sql, (err, result) => {
          if (err) {
            obj = {
              code: 400,
              data: {
                msg: err,
              },
            };
          } else {
            var resultStr = JSON.stringify(result);
            var json = JSON.parse(resultStr);
            obj = {
              code: 200,
              data: json,
            };
            conn.release();
          }
          resolve(obj);
        });
      }
    });
  });
};

module.exports = querys;
